package com.lagou.edu.service.impl;

import com.lagou.edu.dao.AuthCodeDao;
import com.lagou.edu.pojo.AuthCode;
import com.lagou.edu.service.AuthCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class AuthCodeServiceImpl implements AuthCodeService {

    @Autowired
    private AuthCodeDao authCodeDao;

    private String newAuthCode() {
        String code = "";

        for (int i = 0; i < 6; i++) {
            code += (int)(Math.random()*10);
        }

        return code;
    }

    @Override
    public String generateAuthCode(String email) {
        Date now = new Date();
        AuthCode authCode = authCodeDao.findOneByEmail(email);


        if (authCode == null) {
            authCode = new AuthCode();
        }

        String code = newAuthCode();

        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreatetime(now);
        authCode.setExpiretime(new Date(now.getTime() + 600000));

        authCodeDao.save(authCode);

        return code;
    }

    @Override
    public int compareAuthCode(String email, String code) {
        Date now = new Date();
        AuthCode authCode = authCodeDao.findOneByEmail(email);

        if (authCode == null) {
            return 2;   // 验证码不存在，算作验证码超时
        } else if (new Date().compareTo(authCode.getExpiretime()) > 0) {
            return 2;   // 超时
        } else if (!code.equals(authCode.getCode())) {
            return 1;  // 验证码错误
        } else {
            return 0;   // 验证码正确
        }
    }
}
